<template>
    <div class="full" style="overflow:hidden; background:#eee">

        <div class="full uiouter">
            <canvas ref="refCanvas" class="full" style="background-color:white"></canvas>
        </div>

        <!-- 组件菜单 -->
        <SideDrawer ref="refDrawer" :width="250" :popout="bDrawerPopout">

            <div class="noselect" style="height:100%; overflow: hidden;">
                <WidgetMenu ref="refMenu" v-show="sDrawerComponent=='menu'"
                    @drag-start="bShowToolbar=false"
                    @drag-cancel="bShowToolbar=true"
                    @create-new-widget="onCreateNewWidget"
                ></WidgetMenu>
                <!-- <WidgetList v-show="sDrawerComponent=='tree'" :model="model"></WidgetList> -->
                <Setting ref="refSetting" v-show="sDrawerComponent=='setting'"></Setting>
            </div>

            <template #toolbar>
                <div v-if="bShowToolbar" class="toolbar column start gap5" style="margin-left:5px; margin-top:10px; pointer-events:auto">
                    <n-button class="toolbtn" circle size="large" v-show="!bEditing" @click="setEditMode(true)">
                        <n-icon><Pencil /></n-icon>
                    </n-button>
                    <n-button class="toolbtn" circle size="large" icon="select" v-show="bEditing" @click="setEditMode(false)"
                            style="background-color: #38d038; color: white;">
                        <n-icon><Checkmark28Filled /></n-icon>
                    </n-button>
                    
                    <n-button class="toolbtn" circle size="large" v-show="bDrawerPopout" @click="bDrawerPopout=false">
                        <n-icon><ChevronLeft /></n-icon>
                    </n-button>

                    <n-button class="toolbtn" circle size="large" v-show="bEditing" @click="popinDrawer('menu')">
                        <n-icon><PlusOutlined /></n-icon>
                    </n-button>
                    <!-- <n-button class="toolbtn" circle size="large" icon="ios-list" v-show="bEditing" @click="popinDrawer('tree')" title="对象树"></n-button> -->
                    <n-button class="toolbtn" circle size="large" v-show="bEditing && !!activeWidget" @click="popinDrawer('setting')" title="设置">
                        <n-icon><Options /></n-icon>
                    </n-button>

                    
                    
                    <n-popconfirm positive-text="删除" :positive-button-props="{color:'red'}" negative-text="取消" @positive-click="onDeleteActiveWidget">
                        <template #icon>
                            <n-icon color="red"><Delete /></n-icon>
                        </template>
                        <template #trigger>
                            <n-button v-show="bEditing && !!activeWidget" 
                                    class="toolbtn" circle size="large"
                                    style="background-color: rgba(255, 0, 0, 0.49);color: white;">
                                <n-icon><Delete /></n-icon>
                            </n-button>
                        </template>
                        删除UI对象
                    </n-popconfirm>
                </div>
            </template>
            
        </SideDrawer>

    </div>
</template>
<style scoped>
.toolbar .n-button {
    margin-left: 0px ;
}
</style>


<script lang="ts" setup>
import { AppModel } from '../../../model/AppModel'
import WidgetMenu from "./WidgetMenu.vue"
import Setting from "./Setting.vue"
import SideDrawer from '../../common/SideDrawer.vue'
import { reactive, ref, onMounted, Ref } from 'vue'
// import BeUI from "../../../../beui/asm.js/ts/BeUI"
// import Editor from "../../../../beui/asm.js/ts/Editor"
// import Widget from '../../../../beui/asm.js/ts/widgets/Widget';
import * as lv  from "../../../lvgl"
import WidgetLib from './WidgetLib'
import {bus} from '../@beshell/events-ts/bus';
import { conn } from '../@beshell/conn-ts/Connection';
import { LvglEditor } from './LvglEditor'


import {Options, PlaySharp} from '@vicons/ionicons5'
import {ChevronLeft, Delete} from '@vicons/carbon'
import {PlusOutlined} from '@vicons/antd'
import {Pencil} from '@vicons/tabler'
import {Checkmark28Filled} from '@vicons/fluent'

    
let model: AppModel

// let $drawer: any
let $canvas: any

const bDrawerPopout = ref(false)
const sDrawerComponent = ref('menu')

const bEditing = ref(false)
const bShowToolbar = ref(true)

const activeWidget = ref(null) as Ref<lv.Obj|null>

const refCanvas = ref(null) as unknown as Ref<HTMLCanvasElement>
const refSetting = ref(null) as unknown as Ref<typeof Setting>


let canvasDrv: lv.CanvasDispDrv
let canvasDisp: lv.Disp
let editor: LvglEditor

onMounted (function() {

    $canvas = $(refCanvas.value)
    ;(window as any).uicanvas = refCanvas.value

    // 将ui消息转发到远程零件
    // ; (Module as any).emitGlobalEvent = function( emitterPtr:number, eventName:string, dataPtr: number ) {
    //     if( !connection.isConnected )
    //         return
    //     let emitter = Module.object(emitterPtr, false)
    //     if(!emitter || !emitter.name ) {
    //         return
    //     }
    //     console.log(emitter, eventName, Module.object(dataPtr, false))
    //     // connection.console.run(`be.ui.emit()`)
    // }
    // Module.ccall('be_global_event_on')
})

let inited = false
function initLVGL(canvas: HTMLCanvasElement) {
    if(inited) {
        return
    }
    inited = true

    lv.init()
    console.log("initLVGL")

    canvasDrv = new lv.CanvasDispDrv(canvas)
    canvasDisp = canvasDrv.setup()

    editor = new LvglEditor(canvasDisp, (cb)=>{
        model.ui.each(cb)
    })
    editor.on("active-changed", (widget:lv.Obj)=>{
        activeWidget.value = widget
        refSetting.value.setWidget(widget, editor)
        ;(window as any).widget = widget

    })

    ;(window as any).disp = canvasDisp
}
;(window as any).WASMObject = lv.WASMObject
;(window as any).lv = lv

// 创建新widget
function onCreateNewWidget(clazz: any, x: number, y: number){

    if(!model) {
        bShowToolbar.value = true
        return
    }

    if(runtime.platform=='nw.js') {
        $canvas.one('mousemove', (e: MouseEvent)=>{
            // 左键已经松开
            if((e.buttons&1)==0) {
                bShowToolbar.value = true
                return
            }
            $(document).one('mouseup', ()=>{
                bShowToolbar.value = true
            })
            let widget = createAndPlace(clazz,e.offsetX, e.offsetY)

            editor.setActive(widget)
            editor.helper.updateLayout()
            

            canvasDrv.indevData?.setState("released")
            canvasDrv.indevDrv?.tick()
            canvasDrv.indevData?.setState("pressed")
            canvasDrv.indevDrv?.tick()

        })
    }

    else if(runtime.platform=='h5+app'){
        // [x,y] = beui.cacheMouseInput.clientToCanvas(x, y)
        
        // let widget = createAndPlace(clazz, x, y)

        // this.editor.setActive(widget)

        // this.beui.cacheMouseInput.watchTouchEvent(document.documentElement, true, ()=>{
        //     bShowToolbar.value = true
        // })

        // this.beui.cacheMouseInput.setEvent(x, y, true, false, false)
    }

    else {
        bShowToolbar.value = true
    }
}
    
function createAndPlace (clazz: any, offsetX:number, offsetY:number) {
    let widget = new clazz(canvasDisp.actScr())
    
    ;(window as any).widget = widget
    model.ui.appendNewWidget(widget)

    // // 拖放新widget
    widget.setCoords(offsetX-widget.width()/2, offsetY-widget.height()/2)
    
    widget.updateLayout()

    return widget
}


function loadModelWidgets(model: AppModel) {
    if(!model.uiJson)
        return
    for(let wid in model.uiJson.widgets) {
        let json = model.uiJson.widgets[wid]
        let widget = lv.fromJson(json, canvasDisp.actScr())
        model.ui.appendNewWidget(widget)
    }
}

function clearWidgets() {
    canvasDisp && canvasDisp.actScr().clean()
}

function setEditMode(_bEditing: boolean, bMsg=true) {

    bEditing.value = _bEditing

    setTimeout(()=>{

        if(bEditing.value) {
            if(bMsg) {
                window.$message.info("进入UI编辑模式")
            }
            
            editor?.enable()
        }
        else {
            if(bMsg) {
                window.$message.info("退出UI编辑模式")
            }

            editor?.disable()
            
            popoutDrawer()
        }

    }, 0)

}

// 打开
function popinDrawer(component='menu') {
    sDrawerComponent.value = component
    bDrawerPopout.value = true
}
// 关闭
function popoutDrawer() {
    bDrawerPopout.value = false
}

function onDeleteActiveWidget() {
    if(!activeWidget.value || !model)
        return
    
    editor.setActive(null)
    model.ui.removeWidget(activeWidget.value.id)
    activeWidget.value.del()
    activeWidget.value = null
}


function onResize(width: number, height: number) {
    refCanvas.value.width = Math.floor(width)
    refCanvas.value.height = Math.floor(height)
    $canvas.width(width)
    $canvas.height(height)

    initLVGL(refCanvas.value)
}


function setModel(_model: AppModel) {
    model = _model
    
    clearWidgets()
    
    if(model) {
        // 加载组件
        loadModelWidgets(model)

        setEditMode(false, false)
    }
}
function enter() {
    console.log("enter ui", refCanvas.value.width, refCanvas.value.height)
    // initLVGL(refCanvas.value)
}
function leave() {
    setEditMode(false, false)
}

defineExpose({
    leave ,
    enter ,
    setModel ,
    onResize
})
</script>